<template>
  <div class="flash-sale-page">
    <div class="page-header">
      <div class="header-left">
        <h2>限时特惠</h2>
      </div>
      <div class="header-right">
        <a-button type="primary" @click="handleCreateFlashSale">
          <template #icon><icon-plus /></template>
          创建特惠
        </a-button>
      </div>
    </div>

    <!-- 数据概览 -->
    <a-row :gutter="16" class="data-overview">
      <a-col :span="6">
        <a-card class="overview-card">
          <statistic
            title="今日特惠场次"
            :value="statistics.todaySessions"
            :value-style="{ color: '#FF7D00' }"
          >
            <template #suffix>
              <icon-clock-circle style="color: &quot;#FF7D00&quot;" />
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="overview-card">
          <statistic
            title="特惠商品数"
            :value="statistics.productCount"
            :value-style="{ color: '#14C9C9' }"
          >
            <template #suffix>
              <icon-gift style="color: &quot;#14C9C9&quot;" />
            </template>
          </statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="overview-card">
          <statistic
            title="今日成交额"
            :value="statistics.todaySales"
            :precision="2"
            prefix="¥"
            :value-style="{ color: '#FF7D00' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="overview-card">
          <statistic
            title="抢购转化率"
            :value="statistics.conversionRate"
            suffix="%"
            :value-style="{ color: '#16CA45' }"
          />
        </a-card>
      </a-col>
    </a-row>

    <!-- 场次时间轴 -->
    <a-card class="sessions-card">
      <template #title>
        <div class="card-title">
          <span>场次管理</span>
          <a-radio-group v-model="currentDate" type="button" size="small">
            <a-radio value="today">今天 {{ formatDate(new Date()) }}</a-radio>
            <a-radio value="tomorrow"
              >明天 {{ formatDate(getTomorrow()) }}</a-radio
            >
          </a-radio-group>
        </div>
      </template>
      <div class="session-timeline">
        <div
          v-for="session in sessions"
          :key="session.time"
          class="session-item"
          :class="{
            active: session.status === 'active',
            upcoming: session.status === 'upcoming',
            ended: session.status === 'ended',
          }"
          @click="handleSessionClick(session)"
        >
          <div class="time">{{ session.time }}</div>
          <div class="status">{{ getSessionStatusText(session.status) }}</div>
          <div class="stats">
            <div>商品 {{ session.productCount }}</div>
            <div>销量 {{ session.soldCount }}</div>
          </div>
        </div>
      </div>
    </a-card>

    <!-- 活动商品列表 -->
    <a-card class="products-card">
      <template #title>
        <div class="card-title">
          <span>商品管理</span>
          <div class="title-actions">
            <a-select
              v-model="filterForm.status"
              placeholder="商品状态"
              style="width: 120px"
              allow-clear
            >
              <a-option value="all">全部状态</a-option>
              <a-option value="selling">抢购中</a-option>
              <a-option value="upcoming">待开始</a-option>
              <a-option value="ended">已结束</a-option>
              <a-option value="soldout">已售罄</a-option>
            </a-select>
            <a-input-search
              v-model="filterForm.keyword"
              placeholder="搜索商品名称"
              style="width: 200px"
              allow-clear
              @search="handleSearch"
            />
            <a-button type="primary" @click="handleAddProducts">
              <template #icon><icon-plus /></template>
              添加商品
            </a-button>
          </div>
        </div>
      </template>

      <a-table
        :data="productList"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
      >
        <template #columns>
          <a-table-column title="商品信息">
            <template #title>
              <div class="column-title">
                商品信息
                <div class="sort-buttons">
                  <icon-up
                    :class="{
                      active:
                        sortKeys.field === 'name' &&
                        sortKeys.order === 'ascend',
                    }"
                    @click="handleSort('name', 'ascend')"
                  />
                  <icon-down
                    :class="{
                      active:
                        sortKeys.field === 'name' &&
                        sortKeys.order === 'descend',
                    }"
                    @click="handleSort('name', 'descend')"
                  />
                </div>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="product-info">
                <a-image :src="record.image" :width="80" height="80" />
                <div class="info-content">
                  <h4>{{ record.name }}</h4>
                  <div class="tags">
                    <a-tag v-if="record.isHot" color="red">爆品</a-tag>
                    <a-tag v-if="record.isNew" color="green">新品</a-tag>
                  </div>
                  <div class="category">{{ record.category }}</div>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="价格信息" align="center">
            <template #title>
              <div class="column-title">
                价格信息
                <div class="sort-buttons">
                  <icon-up
                    :class="{
                      active:
                        sortKeys.field === 'flashPrice' &&
                        sortKeys.order === 'ascend',
                    }"
                    @click="handleSort('flashPrice', 'ascend')"
                  />
                  <icon-down
                    :class="{
                      active:
                        sortKeys.field === 'flashPrice' &&
                        sortKeys.order === 'descend',
                    }"
                    @click="handleSort('flashPrice', 'descend')"
                  />
                </div>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="price-info">
                <div class="flash-price">
                  <span class="label">特惠价</span>
                  <span class="value">¥{{ record.flashPrice }}</span>
                </div>
                <div class="original-price">
                  <span class="label">原价</span>
                  <span class="value">¥{{ record.originalPrice }}</span>
                </div>
                <div class="discount">
                  <span class="value">{{ calculateDiscount(record) }}折</span>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="库存/限购" align="center">
            <template #title>
              <div class="column-title">
                库存/限购
                <div class="sort-buttons">
                  <icon-up
                    :class="{
                      active:
                        sortKeys.field === 'remainStock' &&
                        sortKeys.order === 'ascend',
                    }"
                    @click="handleSort('remainStock', 'ascend')"
                  />
                  <icon-down
                    :class="{
                      active:
                        sortKeys.field === 'remainStock' &&
                        sortKeys.order === 'descend',
                    }"
                    @click="handleSort('remainStock', 'descend')"
                  />
                </div>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="stock-info">
                <div class="total">总库存：{{ record.totalStock }}</div>
                <div class="remain">剩余：{{ record.remainStock }}</div>
                <div class="limit" v-if="record.limitPerUser">
                  限购：{{ record.limitPerUser }}件/人
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="活动场次" align="center">
            <template #title>
              <div class="column-title">
                活动场次
                <div class="sort-buttons">
                  <icon-up
                    :class="{
                      active:
                        sortKeys.field === 'sessionTime' &&
                        sortKeys.order === 'ascend',
                    }"
                    @click="handleSort('sessionTime', 'ascend')"
                  />
                  <icon-down
                    :class="{
                      active:
                        sortKeys.field === 'sessionTime' &&
                        sortKeys.order === 'descend',
                    }"
                    @click="handleSort('sessionTime', 'descend')"
                  />
                </div>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="session-info">
                <div class="time">{{ record.sessionTime }}</div>
                <a-tag :color="getStatusColor(record.status)">
                  {{ record.status }}
                </a-tag>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="数据统计" align="center">
            <template #title>
              <div class="column-title">
                数据统计
                <div class="sort-buttons">
                  <icon-up
                    :class="{
                      active:
                        sortKeys.field === 'soldCount' &&
                        sortKeys.order === 'ascend',
                    }"
                    @click="handleSort('soldCount', 'ascend')"
                  />
                  <icon-down
                    :class="{
                      active:
                        sortKeys.field === 'soldCount' &&
                        sortKeys.order === 'descend',
                    }"
                    @click="handleSort('soldCount', 'descend')"
                  />
                </div>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="stats-info">
                <div class="item">
                  <span class="label">销量</span>
                  <span class="value">{{ record.soldCount }}</span>
                </div>
                <div class="item">
                  <span class="label">浏览量</span>
                  <span class="value">{{ record.viewCount }}</span>
                </div>
                <div class="item">
                  <span class="label">转化率</span>
                  <span class="value">{{ calculateConversion(record) }}%</span>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="操作" align="right" width="180">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-button
                  type="text"
                  size="small"
                  status="warning"
                  v-if="record.status === 'selling'"
                  @click="handlePause(record)"
                >
                  暂停
                </a-button>
                <a-dropdown position="br">
                  <a-button type="text" size="small">
                    更多<icon-down />
                  </a-button>
                  <template #content>
                    <a-doption @click="handlePreview(record)"
                      >预览商品</a-doption
                    >
                    <a-doption @click="handleCopy(record)">复制商品</a-doption>
                    <a-doption @click="handleShare(record)">分享商品</a-doption>
                    <a-divider style="margin: 4px 0" />
                    <a-doption @click="handleDelete(record)" class="danger">
                      删除商品
                    </a-doption>
                  </template>
                </a-dropdown>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑特惠商品弹窗 -->
    <a-modal
      v-model:visible="showModal"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="800px"
    >
      <a-form :model="formData" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item field="product" label="选择商品" required>
              <div class="selected-product" v-if="formData.product">
                <a-image
                  :src="formData.product.image"
                  :width="60"
                  height="60"
                />
                <div class="product-detail">
                  <div class="name">{{ formData.product.name }}</div>
                  <div class="price">原价：¥{{ formData.product.price }}</div>
                </div>
                <a-button type="text" @click="handleChangeProduct"
                  >更换商品</a-button
                >
              </div>
              <a-button v-else type="outline" @click="handleChangeProduct">
                <template #icon><icon-plus /></template>
                选择商品
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="session" label="活动场次" required>
              <a-select v-model="formData.session" placeholder="请选择活动场次">
                <a-option
                  v-for="session in availableSessions"
                  :key="session.time"
                  :value="session.time"
                >
                  {{ session.date }} {{ session.time }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="flashPrice" label="特惠价" required>
              <a-input-number
                v-model="formData.flashPrice"
                :min="0"
                :max="formData.product?.price"
                :precision="2"
                style="width: 100%"
              >
                <template #prefix>¥</template>
              </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="stock" label="活动库存" required>
              <a-input-number
                v-model="formData.stock"
                :min="1"
                :max="formData.product?.stock"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="limitPerUser" label="每人限购">
              <a-input-number
                v-model="formData.limitPerUser"
                :min="0"
                placeholder="0表示不限购"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item field="settings" label="活动设置">
          <a-space direction="vertical" :style="{ width: '100%' }">
            <a-checkbox v-model="formData.settings.isHot">设为爆品</a-checkbox>
            <a-checkbox v-model="formData.settings.isNew">设为新品</a-checkbox>
            <a-checkbox v-model="formData.settings.memberOnly"
              >仅会员可购</a-checkbox
            >
            <a-checkbox v-model="formData.settings.newUserOnly"
              >仅新用户可购</a-checkbox
            >
          </a-space>
        </a-form-item>

        <a-form-item field="notice" label="活动提醒">
          <a-space direction="vertical" :style="{ width: '100%' }">
            <a-checkbox v-model="formData.notice.enableRemind"
              >开启活动提醒</a-checkbox
            >
            <a-input-number
              v-if="formData.notice.enableRemind"
              v-model="formData.notice.remindTime"
              :min="1"
              :max="60"
              style="width: 100px"
            >
              <template #append>分钟前</template>
            </a-input-number>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import {
  IconPlus,
  IconDown,
  IconClockCircle,
  IconGift,
  IconSearch,
} from "@arco-design/web-vue/es/icon";

// 数据概览
const statistics = reactive({
  todaySessions: 6,
  productCount: 128,
  todaySales: 15680.5,
  conversionRate: 35.8,
});

// 场次数据
const currentDate = ref("today");
const sessions = ref([
  {
    time: "10:00",
    status: "ended",
    productCount: 35,
    soldCount: 28,
  },
  {
    time: "12:00",
    status: "ended",
    productCount: 42,
    soldCount: 35,
  },
  {
    time: "14:00",
    status: "active",
    productCount: 38,
    soldCount: 15,
  },
  {
    time: "16:00",
    status: "upcoming",
    productCount: 45,
    soldCount: 0,
  },
  {
    time: "18:00",
    status: "upcoming",
    productCount: 40,
    soldCount: 0,
  },
  {
    time: "20:00",
    status: "upcoming",
    productCount: 50,
    soldCount: 0,
  },
]);

// 筛选表单
const filterForm = reactive({
  status: "all",
  keyword: "",
});

// 商品列表数据
const loading = ref(false);
const productList = ref([
  {
    id: 1,
    name: "特色桂林米粉",
    image: "https://example.com/product1.jpg",
    category: "地方特产",
    isHot: true,
    isNew: false,
    flashPrice: 9.9,
    originalPrice: 15.0,
    totalStock: 1000,
    remainStock: 850,
    limitPerUser: 2,
    sessionTime: "14:00",
    status: "selling",
    soldCount: 150,
    viewCount: 2580,
    conversionRate: 5.8,
  },
  {
    id: 2,
    name: "桂林辣椒酱",
    image: "https://example.com/product2.jpg",
    category: "调味品",
    isHot: false,
    isNew: true,
    flashPrice: 12.9,
    originalPrice: 20.0,
    totalStock: 500,
    remainStock: 486,
    limitPerUser: 3,
    sessionTime: "16:00",
    status: "upcoming",
    soldCount: 0,
    viewCount: 1200,
    conversionRate: 0,
  },
]);

// 分页配置
const pagination = reactive({
  total: 100,
  current: 1,
  pageSize: 10,
});

// 表单数据
const showModal = ref(false);
const modalTitle = ref("添加特惠商品");
const formData = reactive({
  product: null,
  session: "",
  flashPrice: 0,
  stock: 0,
  limitPerUser: 0,
  settings: {
    isHot: false,
    isNew: false,
    memberOnly: false,
    newUserOnly: false,
  },
  notice: {
    enableRemind: false,
    remindTime: 30,
  },
});

// 可选场次
const availableSessions = computed(() => {
  return sessions.value
    .filter((s) => s.status === "upcoming")
    .map((s) => ({
      time: s.time,
      date: currentDate.value === "today" ? "今天" : "明天",
    }));
});

// 排序状态
const sortKeys = reactive({
  field: "",
  order: "",
});

// 方法
const formatDate = (date) => {
  return date.toLocaleDateString("zh-CN", { month: "2-digit", day: "2-digit" });
};

const getTomorrow = () => {
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  return tomorrow;
};

const getSessionStatusText = (status) => {
  const statusMap = {
    active: "抢购中",
    upcoming: "即将开始",
    ended: "已结束",
  };
  return statusMap[status] || status;
};

const getStatusColor = (status) => {
  const colors = {
    selling: "green",
    upcoming: "blue",
    ended: "gray",
    soldout: "red",
  };
  return colors[status] || "gray";
};

const calculateDiscount = (record) => {
  return ((record.flashPrice / record.originalPrice) * 10).toFixed(1);
};

const calculateConversion = (record) => {
  if (!record.viewCount) return 0;
  return ((record.soldCount / record.viewCount) * 100).toFixed(1);
};

const handleSessionClick = (session) => {
  // 实现场次切换逻辑
};

const handleSearch = () => {
  loading.value = true;
  // 实现搜索逻辑
  setTimeout(() => {
    loading.value = false;
  }, 1000);
};

const handleAddProducts = () => {
  showModal.value = true;
  modalTitle.value = "添加特惠商品";
  Object.assign(formData, {
    product: null,
    session: "",
    flashPrice: 0,
    stock: 0,
    limitPerUser: 0,
    settings: {
      isHot: false,
      isNew: false,
      memberOnly: false,
      newUserOnly: false,
    },
    notice: {
      enableRemind: false,
      remindTime: 30,
    },
  });
};

const handleChangeProduct = () => {
  // 实现商品选择逻辑
};

const handleEdit = (record) => {
  showModal.value = true;
  modalTitle.value = "编辑特惠商品";
  Object.assign(formData, {
    product: {
      image: record.image,
      name: record.name,
      price: record.originalPrice,
    },
    session: record.sessionTime,
    flashPrice: record.flashPrice,
    stock: record.totalStock,
    limitPerUser: record.limitPerUser,
    settings: {
      isHot: record.isHot,
      isNew: record.isNew,
      memberOnly: false,
      newUserOnly: false,
    },
  });
};

const handlePause = (record) => {
  Modal.warning({
    title: "确认暂停",
    content: "暂停后该商品将不再显示在特惠活动中，确定要暂停吗？",
    onOk: () => {
      Message.success("已暂停特惠商品");
    },
  });
};

const handlePreview = (record) => {
  // 实现预览逻辑
};

const handleCopy = (record) => {
  // 实现复制逻辑
  Message.success("复制成功");
};

const handleShare = (record) => {
  // 实现分享逻辑
};

const handleDelete = (record) => {
  Modal.warning({
    title: "确认删除",
    content: "确定要删除该特惠商品吗？删除后无法恢复。",
    onOk: () => {
      Message.success("删除成功");
    },
  });
};

const handleModalOk = () => {
  // 实现保存逻辑
  showModal.value = false;
  Message.success("保存成功");
};

const handleModalCancel = () => {
  showModal.value = false;
};

const onPageChange = (page) => {
  pagination.current = page;
  // 实现分页加载逻辑
};

// 排序处理函数
const handleSort = (field, order) => {
  if (sortKeys.field === field && sortKeys.order === order) {
    // 取消排序
    sortKeys.field = "";
    sortKeys.order = "";
    productList.value = [...originalProductList];
    Message.success("已取消排序");
    return;
  }

  sortKeys.field = field;
  sortKeys.order = order;

  const sortedList = [...productList.value];
  sortedList.sort((a, b) => {
    let compareA = field.includes(".")
      ? field.split(".").reduce((obj, key) => obj[key], a)
      : a[field];
    let compareB = field.includes(".")
      ? field.split(".").reduce((obj, key) => obj[key], b)
      : b[field];

    // 处理特殊字段
    if (field === "flashPrice" || field === "originalPrice") {
      compareA = parseFloat(compareA) || 0;
      compareB = parseFloat(compareB) || 0;
    } else if (field === "sessionTime") {
      compareA = compareA.replace(":", "");
      compareB = compareB.replace(":", "");
    } else if (
      field === "soldCount" ||
      field === "viewCount" ||
      field === "remainStock"
    ) {
      compareA = parseInt(compareA) || 0;
      compareB = parseInt(compareB) || 0;
    }

    if (order === "ascend") {
      return compareA > compareB ? 1 : -1;
    } else {
      return compareA < compareB ? 1 : -1;
    }
  });

  productList.value = sortedList;
  Message.success(`${order === "ascend" ? "升序" : "降序"}排序成功`);
};

// 保存原始列表数据
const originalProductList = [...productList.value];
</script>

<style lang="scss" scoped>
.flash-sale-page {
  padding: 24px;

  .page-header {
    @apply flex items-center justify-between mb-6;

    .header-left {
      h2 {
        @apply text-xl font-medium m-0;
      }
    }
  }

  .data-overview {
    @apply mb-6;

    .overview-card {
      @apply text-center;
    }
  }

  .sessions-card {
    @apply mb-6;

    .card-title {
      @apply flex items-center justify-between;
    }

    .session-timeline {
      @apply flex gap-4 mt-4;

      .session-item {
        @apply flex-1 p-4 rounded-lg cursor-pointer transition-all duration-300 border border-gray-200;

        &.active {
          @apply bg-primary-50 border-primary-200;

          .time {
            @apply text-primary-600;
          }
        }

        &.upcoming {
          @apply bg-gray-50;

          &:hover {
            @apply bg-gray-100;
          }
        }

        &.ended {
          @apply bg-gray-100 cursor-not-allowed;

          .time {
            @apply text-gray-500;
          }
        }

        .time {
          @apply text-lg font-medium mb-2;
        }

        .status {
          @apply text-sm text-gray-600 mb-2;
        }

        .stats {
          @apply text-xs text-gray-500;
        }
      }
    }
  }

  .products-card {
    .card-title {
      @apply flex items-center justify-between;

      .title-actions {
        @apply flex items-center gap-4;
      }
    }

    .product-info {
      @apply flex gap-4;

      .info-content {
        @apply flex-1;

        h4 {
          @apply m-0 mb-2 font-medium;
        }

        .tags {
          @apply mb-2;
        }

        .category {
          @apply text-sm text-gray-500;
        }
      }
    }

    .price-info {
      .flash-price {
        @apply mb-2;

        .label {
          @apply text-sm text-gray-500 mr-2;
        }

        .value {
          @apply text-lg font-medium text-red-500;
        }
      }

      .original-price {
        @apply mb-1;

        .label {
          @apply text-sm text-gray-500 mr-2;
        }

        .value {
          @apply text-sm line-through text-gray-400;
        }
      }

      .discount {
        .value {
          @apply text-sm text-orange-500;
        }
      }
    }

    .stock-info {
      @apply text-sm text-gray-600 space-y-1;
    }

    .session-info {
      .time {
        @apply mb-2 font-medium;
      }
    }

    .stats-info {
      .item {
        @apply mb-2 last:mb-0;

        .label {
          @apply text-sm text-gray-500 mr-2;
        }

        .value {
          @apply font-medium;
        }
      }
    }
  }

  .selected-product {
    @apply flex items-center gap-4 p-4 border rounded-lg;

    .product-detail {
      @apply flex-1;

      .name {
        @apply mb-1 font-medium;
      }

      .price {
        @apply text-sm text-gray-500;
      }
    }
  }
}

:deep(.arco-dropdown-option.danger) {
  color: rgb(var(--danger-6));
}

.column-title {
  display: flex;
  align-items: center;
  gap: 8px;

  .sort-buttons {
    display: inline-flex;
    flex-direction: column;
    gap: 2px;
    margin-left: 4px;

    :deep(.arco-icon) {
      font-size: 12px;
      color: var(--color-text-3);
      cursor: pointer;
      line-height: 1;
      padding: 2px;

      &:hover,
      &.active {
        color: rgb(var(--primary-6));
      }
    }
  }
}
</style>
